//
//  XYOAuthController.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 15/12/29.
//  Copyright © 2015年 cn.weibo. All rights reserved.
//

import UIKit

class XYOAuthController: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpNav()
        
        view.addSubview(webView)
        
    }
    private func setUpNav() {
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", action: "autoWriteClick", target: self)
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", action: "dissMissClick", target: self)
    }
    @objc private func autoWriteClick() {
        
        /**
         document.getElementById('userId').value='ssssss';
         document.getElementById('passwd').value='aaaaa';
         */
         // JS 注入
        let jsString = "document.getElementById('userId').value='15149363409';document.getElementById('passwd').value='zhouxingyu123';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    @objc private func dissMissClick() {
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: 懒加载控件
    private lazy var webView: UIWebView = {
        
        let webView = UIWebView()
        webView.frame = self.view.bounds
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirect_uri)"
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
        
        webView.delegate = self
        
        return webView
    }()
    // MARK: UIWebViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlStrinrg = request.URL?.absoluteString else{
            
            return true
        }
        // 判断是否在加载回调页
        if !urlStrinrg.hasPrefix(redirect_uri) {
            return true
        }
        // 来到这个地方说明是回调页
        if let query = request.URL?.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex("code=".endIndex)
           
            XYUserAccountViewModel.sharedUserAccountViewModel.getUserAccessToken(code, complete: { (isSuccess) -> () in
                
                if isSuccess {
                    // 先关闭model的控制器 然后发送切换根控制器的通知
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 切换控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(changeRootViewControllerNotification, object: self)
                    })
                }else{
                    print("请求失败")
                }
                
            })
            
            
        }else{  // 说明用户点击了取消
            dissMissClick()

        }
        
        return false
    }
}

